package queue_seqnumber

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ QueueSeqnumberModel = (*customQueueSeqnumberModel)(nil)

type (
	// QueueSeqnumberModel is an interface to be customized, add more methods here,
	// and implement the added methods in customQueueSeqnumberModel.
	QueueSeqnumberModel interface {
		queueSeqnumberModel
		FindCout(ctx context.Context, id string) (int64, error)
		InsertTranCtx(ctx context.Context, sesstion sqlx.Session, data *QueueSeqnumber) (sql.Result, error)
		FindLastId(ctx context.Context, groupid string) (*QueueSeqnumber, error)
	}

	customQueueSeqnumberModel struct {
		*defaultQueueSeqnumberModel
	}
)

// NewQueueSeqnumberModel returns a model for the database table.
func NewQueueSeqnumberModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) QueueSeqnumberModel {
	return &customQueueSeqnumberModel{
		defaultQueueSeqnumberModel: newQueueSeqnumberModel(conn, c, opts...),
	}
}

type (
	QueueNumber struct {
		TotalCount sql.NullInt64 `db:"totalCount"` //总数
	}
)

// InsertTranCtx 事务插入
func (m *defaultQueueSeqnumberModel) InsertTranCtx(ctx context.Context, sesstion sqlx.Session, data *QueueSeqnumber) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?,?, ?, ?, ?, ?, ?, ?)", m.table, queueSeqnumberRowsExpectAutoSet)
	ret, err := sesstion.ExecCtx(ctx, query, data.Groupid, data.Deptid, data.Roomid, data.Doctorid, data.Seatid, data.Registercode, data.Signtime, data.Startseattime, data.Endseattime, data.Carettime)
	return ret, err
}

func (m *defaultQueueSeqnumberModel) FindCout(ctx context.Context, groupid string) (int64, error) {
	var resp QueueNumber
	query := fmt.Sprintf("SELECT count(*) as totalCount FROM callsystem.queue_seqnumber where groupid=?")
	err := m.QueryRowNoCache(&resp, query, groupid)
	if err != nil {
		return 0, err
	}
	switch err {
	case nil:
		return resp.TotalCount.Int64, nil
	case sqlc.ErrNotFound:
		return 0, ErrNotFound
	default:
		return 0, err
	}
}

// FindLastId 查最后一条数据
func (m *defaultQueueSeqnumberModel) FindLastId(ctx context.Context, groupid string) (*QueueSeqnumber, error) {
	var resp QueueSeqnumber
	query := fmt.Sprintf("SELECT * FROM callsystem.queue_seqnumber where groupid=? order by id desc limit 1")
	err := m.QueryRowNoCache(&resp, query, groupid)
	if err != nil {
		return &resp, err
	}
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
